package manager.modulo.clientefornecedor.fonte;

import java.sql.SQLException;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import manager.auxiliares.Configurations;
import manager.auxiliares.FixedLengthDocument;
import manager.auxiliares.Icons;
import manager.auxiliares.MensagemExcessao;
import manager.auxiliares.WindowsFunctions;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.principal.fonte.JanelaLogin;
import manager.modulo.clientefornecedor.dao.CentroCustoDao;
import manager.modulo.clientefornecedor.dao.ClienteFornecedorDao;

/**
 *
 * @author Thiago
 */
public class JanelaCentroCusto extends javax.swing.JFrame {

    //Entrada de Estoque
    int idCentroCusto = 0;

    /**
     * Creates new form UserWindow
     */
    public JanelaCentroCusto(int id) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idCentroCusto = id;
            configurarJanela();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private void configurarCampos() {
        ((TextFieldValidator) jTextField4).validarCampo();
    }

    private LinkedList<String> validarCamposCentroCusto() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField4).validarCampo()) {// Nome
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        return fieldList;
    }

    private int adicionarCentroCusto() {
        try {
            int idCentroCustoBuscado = CentroCustoDao.getIdCentroCustoPorNome(jTextField4.getText());
            if (idCentroCustoBuscado == 0 || idCentroCustoBuscado == idCentroCusto) {
                try {

                    JanelaLogin.connection.setAutoCommit(false);

                    CentroCustoDao centroCustoDao = new CentroCustoDao();

                    centroCustoDao.setIdClienteFornecedor(ClienteFornecedorDao.getIdClienteFornecedorPorIdentificador(jComboBox1.getSelectedItem().toString()));
                    centroCustoDao.setNome(jTextField4.getText());
                    centroCustoDao.setObservacao(jTextArea2.getText());

                    centroCustoDao.inserir();


                    JanelaLogin.connection.commit();
                    JOptionPane.showMessageDialog(null, "Centro de custo cadastrado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();

                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, this.getTitle());
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este centro de custo já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
        return 0;
    }

    private int editarCentroCusto() {
        try {
            int idCentroCustoBuscado = CentroCustoDao.getIdCentroCustoPorNome(jTextField4.getText());
            if (idCentroCustoBuscado == 0 || idCentroCustoBuscado == idCentroCusto) {
                try {

                    JanelaLogin.connection.setAutoCommit(false);

                    CentroCustoDao centroCustoDao = new CentroCustoDao();
                    centroCustoDao.buscar(idCentroCusto);

                    centroCustoDao.setIdClienteFornecedor(ClienteFornecedorDao.getIdClienteFornecedorPorIdentificador(jComboBox1.getSelectedItem().toString()));
                    centroCustoDao.setNome(jTextField4.getText());
                    centroCustoDao.setObservacao(jTextArea2.getText());

                    centroCustoDao.atualizar();

                    JanelaLogin.connection.commit();
                    JOptionPane.showMessageDialog(null, "Centro de custo atualizado com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();

                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, this.getTitle());
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Este centro de custo já esta cadastrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
        return 0;
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());


        CentroCustoDao centroCustoDao = new CentroCustoDao();
        centroCustoDao.buscar(idCentroCusto);
        jTextField4.setText(centroCustoDao.getNome());
        jTextArea2.setText(centroCustoDao.getObservacao());

        ClienteFornecedorDao clienteFornecedorDao = new ClienteFornecedorDao();
        clienteFornecedorDao.buscar(centroCustoDao.getIdClienteFornecedor());
        jComboBox1.setSelectedItem(clienteFornecedorDao.getIdentificador());
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configurarJanela() throws SQLException {

        LinkedList<String> listaClientesFornecedores = ClienteFornecedorDao.getListaIdentificadorClienteFornecedor();
        for (int i = 0; i < listaClientesFornecedores.size(); i++) {
            jComboBox1.addItem(listaClientesFornecedores.get(i).toString());
        }

        if (idCentroCusto != 0) { // Edição de usuário
            carregarInformacoes();
        } else {
            configurarCampos();
        }

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new TextFieldValidator(60, 4, true, true, "text", jLabel7);
        jLabel44 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("CENTRO DE CUSTO");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(570, 180));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(20, 150, 100, 23);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(130, 150, 100, 23);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Nome");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(20, 20, 70, 14);

        jTextField4.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel1.add(jTextField4);
        jTextField4.setBounds(20, 40, 270, 20);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Observação");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 70, 80, 14);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Cliente Fornecedor");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(295, 20, 150, 14);

        jTextArea2.setColumns(20);
        jTextArea2.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(2);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane5.setViewportView(jTextArea2);
        jTextArea2.setDocument(new FixedLengthDocument(100));

        jPanel1.add(jScrollPane5);
        jScrollPane5.setBounds(20, 90, 545, 50);

        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(295, 40, 270, 20);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 570, 180);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 571, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                .addGap(1, 1, 1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposCentroCusto();
        if (fieldValidadeList.size() == 0) {
            if (idCentroCusto == 0) {
                adicionarCentroCusto();
            } else {
                editarCentroCusto();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration//GEN-END:variables
}
